import React, { Component } from 'react';
import Record from './Record';
import * as RecordsAPI from '../utils/RecordsAPI'

class Records extends Component {
  constructor(){
    super();
    this.state = {
      error: null,
      isLoaaded: false,
      records : []
    }
  }
 
  componentDidMount() {
    RecordsAPI.getAll().then(
      response => this.setState({
        records: response.data,
        isLoaded: true
      })
    ).catch(
      error => this.setState({
        isLoaded: true,
        error
      })
    )
  }


  render() {
    const {error, isLoaded, records } = this.state;
    if(error){
      return <div>Error: {error.message}</div>
    }else if(!isLoaded){
      return  <div>loading.....</div>
    }else{
      return (
        <div>
            <h2>Records</h2>
            <table className="table toble-borderred">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Title</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
             
                   {this.state.records.map((record, i) => <Record key={record.id} record = {record} />)}
                 
                </tbody>
            </table>
        </div>
      );
    }
  }
}

export default Records;
